package org.jetnuke.dao.sqlserver;

import org.apache.log4j.Logger;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import net.jforum.JForumExecutionContext;
import net.jforum.util.preferences.SystemGlobals;

import org.jetnuke.dao.PictureDAO;
import org.jetnuke.dao.generic.GenericPictureDAO;

public class SqlServerPictureDAO extends GenericPictureDAO implements
		PictureDAO {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(SqlServerPictureDAO.class);

	public List getLast(int last) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("getLast(int) - start"); //$NON-NLS-1$
		}

		String q1 = SystemGlobals.getSql("GenericModel.selectByLimit");
		String q2 = SystemGlobals.getSql("PictureModel.selectLast");
		PreparedStatement p = JForumExecutionContext.getConnection()
				.prepareStatement(q1 + " " + last + " " + q2);
		ResultSet rs = p.executeQuery();
		List list = this.processSelectAll(rs);
		rs.close();
		p.close();

		if (logger.isDebugEnabled()) {
			logger.debug("getLast(int) - end"); //$NON-NLS-1$
		}
		return list;
	}

	public List getTop(int limit) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("getTop(int) - start"); //$NON-NLS-1$
		}

		String q1 = SystemGlobals.getSql("GenericModel.selectByLimit");
		String q2 = SystemGlobals.getSql("PictureModel.selectTopRated");
		PreparedStatement p = JForumExecutionContext.getConnection()
				.prepareStatement(q1 + " " + limit + " " + q2);
		ResultSet rs = p.executeQuery();
		List list = this.processSelectAll(rs);
		rs.close();
		p.close();

		if (logger.isDebugEnabled()) {
			logger.debug("getTop(int) - end"); //$NON-NLS-1$
		}
		return list;
	}

	public List search(String searchval, int start, int limit) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("search(String, int, int) - start"); //$NON-NLS-1$
		}

		PreparedStatement p;
		String q = SystemGlobals.getSql("PictureModel.search");
		q = q.replaceAll("#start", String.valueOf(start));
		q = q.replaceAll("#limit", String.valueOf(limit));
		String val = "%" + searchval + "%";

		p = JForumExecutionContext.getConnection().prepareStatement(q);
		p.setString(1, val);
		p.setString(2, val);
		p.setString(3, val);
		p.setString(4, val);
		p.setString(5, val);
		p.setString(6, val);
		p.setString(7, val);
		p.setString(8, val);

		ResultSet rs = p.executeQuery();
		List list = this.processSelectAll(rs);
		rs.close();
		p.close();

		if (logger.isDebugEnabled()) {
			logger.debug("search(String, int, int) - end"); //$NON-NLS-1$
		}
		return list;
	}

}
